// 知识库基础类型
export interface KnowledgeBase {
  id: string;
  name: string;
  description?: string;
  category: string;
  tags: string[];
  isPublic: boolean;
  status: "active" | "inactive" | "processing" | "error";
  documentCount: number;
  totalSize: number;
  lastIndexed?: string;
  createdBy: string;
  createdAt: string;
  updatedAt: string;
  settings: KnowledgeBaseSettings;
  stats: KnowledgeBaseStats;
  permissions: KnowledgeBasePermissions;
  metadata?: Record<string, any>;
}

// 知识库设置类型
export interface KnowledgeBaseSettings {
  // 索引设置
  indexing: {
    strategy: "auto" | "manual" | "scheduled";
    chunkSize: number;
    chunkOverlap: number;
    splitMethod: "sentence" | "paragraph" | "token" | "custom";
    customSeparators?: string[];
    preserveStructure: boolean;
    removeHeaders: boolean;
    removeFooters: boolean;
    removeTables: boolean;
    removeImages: boolean;
  };

  // 嵌入设置
  embedding: {
    model: string;
    provider: "openai" | "huggingface" | "cohere" | "local" | "custom";
    dimensions: number;
    batchSize: number;
    maxRetries: number;
    timeout: number;
  };

  // 搜索设置
  search: {
    defaultLimit: number;
    maxLimit: number;
    similarityThreshold: number;
    enableHybridSearch: boolean;
    keywordWeight: number;
    semanticWeight: number;
    enableReranking: boolean;
    rerankingModel?: string;
  };

  // 处理设置
  processing: {
    enableOCR: boolean;
    ocrLanguages: string[];
    enableTranslation: boolean;
    targetLanguages: string[];
    enableSummarization: boolean;
    summaryLength: "short" | "medium" | "long";
    enableKeywordExtraction: boolean;
    maxKeywords: number;
  };

  // 质量控制
  quality: {
    minDocumentSize: number;
    maxDocumentSize: number;
    allowedFileTypes: string[];
    enableDuplicateDetection: boolean;
    duplicateThreshold: number;
    enableContentValidation: boolean;
    validationRules: string[];
  };

  // 安全设置
  security: {
    enableEncryption: boolean;
    encryptionKey?: string;
    enableAccessControl: boolean;
    defaultPermissions: "read" | "write" | "admin" | "none";
    enableAuditLog: boolean;
    retentionDays: number;
  };

  // 备份设置
  backup: {
    enabled: boolean;
    frequency: "daily" | "weekly" | "monthly";
    retentionCount: number;
    includeMetadata: boolean;
    includeEmbeddings: boolean;
    compressionLevel: number;
  };
}

// 知识库统计类型
export interface KnowledgeBaseStats {
  documents: {
    total: number;
    processed: number;
    pending: number;
    failed: number;
    byType: Record<string, number>;
    bySize: {
      small: number; // < 1MB
      medium: number; // 1-10MB
      large: number; // > 10MB
    };
    avgSize: number;
    totalSize: number;
  };

  chunks: {
    total: number;
    avgSize: number;
    avgTokens: number;
    totalTokens: number;
  };

  usage: {
    searches: {
      total: number;
      thisMonth: number;
      avgPerDay: number;
      topQueries: Array<{
        query: string;
        count: number;
        avgRelevance: number;
      }>;
    };

    performance: {
      avgSearchTime: number;
      avgIndexTime: number;
      cacheHitRate: number;
      errorRate: number;
    };
  };

  quality: {
    avgRelevanceScore: number;
    duplicateRate: number;
    processingSuccessRate: number;
    userSatisfactionScore?: number;
  };

  growth: {
    documentsAdded: Array<{
      date: string;
      count: number;
    }>;
    searchVolume: Array<{
      date: string;
      count: number;
    }>;
  };
}

// 知识库权限类型
export interface KnowledgeBasePermissions {
  owner: string;
  collaborators: Array<{
    userId: string;
    username: string;
    role: "viewer" | "editor" | "admin";
    permissions: string[];
    addedAt: string;
    addedBy: string;
  }>;
  teams: Array<{
    teamId: string;
    teamName: string;
    role: "viewer" | "editor" | "admin";
    permissions: string[];
    addedAt: string;
  }>;
  isPublic: boolean;
  publicPermissions: string[];
  inheritFromParent: boolean;
}

// 知识文档类型
export interface KnowledgeDocument {
  id: string;
  knowledgeBaseId: string;
  title: string;
  content?: string;
  type: "text" | "pdf" | "docx" | "html" | "markdown" | "csv" | "json" | "xml";
  mimeType: string;
  size: number;
  url?: string;
  filePath?: string;
  status: "pending" | "processing" | "completed" | "failed" | "archived";
  processingProgress: number;
  error?: string;
  metadata: DocumentMetadata;
  chunks: KnowledgeChunk[];
  chunkCount: number;
  tokenCount: number;
  language?: string;
  encoding?: string;
  checksum: string;
  version: number;
  parentId?: string;
  children?: string[];
  tags: string[];
  createdBy: string;
  createdAt: string;
  updatedAt: string;
  processedAt?: string;
  lastAccessedAt?: string;
  accessCount: number;
}

// 文档元数据类型
export interface DocumentMetadata {
  // 基础信息
  title?: string;
  author?: string;
  subject?: string;
  keywords?: string[];
  description?: string;
  language?: string;

  // 文件信息
  filename: string;
  originalName?: string;
  extension: string;
  mimeType: string;
  size: number;
  pages?: number;
  wordCount?: number;
  characterCount?: number;

  // 时间信息
  createdDate?: string;
  modifiedDate?: string;
  uploadedAt: string;
  processedAt?: string;

  // 处理信息
  ocrApplied?: boolean;
  translationApplied?: boolean;
  sourceLanguage?: string;
  targetLanguage?: string;
  processingTime?: number;

  // 质量信息
  confidence?: number;
  readability?: {
    score: number;
    level: string;
  };
  sentiment?: {
    score: number;
    label: "positive" | "negative" | "neutral";
  };

  // 分类信息
  category?: string;
  topics?: Array<{
    name: string;
    confidence: number;
  }>;
  entities?: Array<{
    text: string;
    type: string;
    confidence: number;
  }>;

  // 自定义字段
  custom?: Record<string, any>;
}

// 知识块类型
export interface KnowledgeChunk {
  id: string;
  documentId: string;
  knowledgeBaseId: string;
  content: string;
  title?: string;
  summary?: string;
  position: {
    start: number;
    end: number;
    page?: number;
    section?: string;
  };
  tokenCount: number;
  characterCount: number;
  embedding?: number[];
  embeddingModel?: string;
  metadata: {
    chunkIndex: number;
    totalChunks: number;
    overlap: number;
    splitMethod: string;
    context?: string;
    headings?: string[];
    tables?: Array<{
      caption?: string;
      data: string[][];
    }>;
    images?: Array<{
      caption?: string;
      url: string;
      description?: string;
    }>;
    links?: Array<{
      text: string;
      url: string;
    }>;
  };
  quality: {
    relevanceScore?: number;
    coherenceScore?: number;
    completenessScore?: number;
    readabilityScore?: number;
  };
  tags: string[];
  createdAt: string;
  updatedAt: string;
}

// 知识查询类型
export interface KnowledgeQuery {
  query: string;
  knowledgeBaseIds?: string[];
  filters?: {
    documentTypes?: string[];
    tags?: string[];
    dateRange?: {
      start: string;
      end: string;
    };
    authors?: string[];
    languages?: string[];
    minRelevance?: number;
    categories?: string[];
  };
  searchType: "semantic" | "keyword" | "hybrid";
  limit?: number;
  offset?: number;
  includeMetadata?: boolean;
  includeSummary?: boolean;
  highlightMatches?: boolean;
  rerank?: boolean;
  rerankingModel?: string;
}

// 向量搜索参数类型
export interface VectorSearchParams {
  vector?: number[];
  query?: string;
  knowledgeBaseIds: string[];
  limit?: number;
  threshold?: number;
  filters?: Record<string, any>;
  includeMetadata?: boolean;
  includeDistance?: boolean;
}

// 知识搜索结果类型
export interface KnowledgeSearchResult {
  results: Array<{
    chunk: KnowledgeChunk;
    document: KnowledgeDocument;
    knowledgeBase: KnowledgeBase;
    relevanceScore: number;
    distance?: number;
    highlights?: string[];
    summary?: string;
    reasoning?: string;
  }>;
  facets?: {
    documentTypes: Array<{ type: string; count: number }>;
    tags: Array<{ tag: string; count: number }>;
    authors: Array<{ author: string; count: number }>;
    languages: Array<{ language: string; count: number }>;
    categories: Array<{ category: string; count: number }>;
  };
  suggestions?: string[];
  total: number;
  queryTime: number;
  processingSteps?: Array<{
    step: string;
    duration: number;
    details?: any;
  }>;
}

// 知识统计类型
export interface KnowledgeStats {
  overview: {
    totalBases: number;
    totalDocuments: number;
    totalChunks: number;
    totalSize: number;
    avgDocumentSize: number;
    processingSuccessRate: number;
  };

  usage: {
    searchesThisMonth: number;
    avgSearchesPerDay: number;
    topQueries: Array<{
      query: string;
      count: number;
      avgRelevance: number;
    }>;
    userEngagement: {
      activeUsers: number;
      avgSessionDuration: number;
      returnUserRate: number;
    };
  };

  performance: {
    avgSearchTime: number;
    avgIndexingTime: number;
    cacheHitRate: number;
    errorRate: number;
    uptime: number;
  };

  quality: {
    avgRelevanceScore: number;
    userSatisfactionScore: number;
    duplicateDetectionRate: number;
    processingAccuracy: number;
  };

  growth: {
    documentsGrowth: Array<{
      date: string;
      count: number;
      cumulative: number;
    }>;
    searchGrowth: Array<{
      date: string;
      count: number;
    }>;
    userGrowth: Array<{
      date: string;
      count: number;
    }>;
  };
}

// 知识分类类型
export interface KnowledgeCategory {
  id: string;
  name: string;
  description?: string;
  icon?: string;
  color?: string;
  parentId?: string;
  children?: KnowledgeCategory[];
  level: number;
  path: string;
  knowledgeBaseCount: number;
  documentCount: number;
  isSystem: boolean;
  order: number;
  createdAt: string;
  updatedAt: string;
}

// 知识标签类型
export interface KnowledgeTag {
  id: string;
  name: string;
  description?: string;
  color?: string;
  category?: string;
  usageCount: number;
  knowledgeBaseCount: number;
  documentCount: number;
  trending: boolean;
  synonyms?: string[];
  relatedTags?: string[];
  createdAt: string;
  updatedAt: string;
}

// 知识导入类型
export interface KnowledgeImport {
  type: "file" | "url" | "api" | "database" | "crawl";
  source: {
    files?: File[];
    urls?: string[];
    apiEndpoint?: string;
    databaseConfig?: {
      type: "mysql" | "postgresql" | "mongodb" | "elasticsearch";
      host: string;
      port: number;
      database: string;
      username: string;
      password: string;
      query?: string;
    };
    crawlConfig?: {
      startUrls: string[];
      maxDepth: number;
      maxPages: number;
      allowedDomains?: string[];
      excludePatterns?: string[];
      respectRobots: boolean;
      delay: number;
    };
  };
  options: {
    knowledgeBaseId: string;
    processImmediately: boolean;
    overwriteExisting: boolean;
    preserveStructure: boolean;
    extractMetadata: boolean;
    enableOCR: boolean;
    enableTranslation: boolean;
    targetLanguage?: string;
    tags?: string[];
    category?: string;
  };
}

// 知识导出类型
export interface KnowledgeExport {
  knowledgeBaseIds: string[];
  format: "json" | "csv" | "xml" | "pdf" | "docx" | "zip";
  options: {
    includeMetadata: boolean;
    includeEmbeddings: boolean;
    includeChunks: boolean;
    includeStats: boolean;
    anonymize: boolean;
    dateRange?: {
      start: string;
      end: string;
    };
    filters?: {
      documentTypes?: string[];
      tags?: string[];
      categories?: string[];
    };
  };
}

// 导出所有类型
export type {
  KnowledgeBase,
  KnowledgeBaseSettings,
  KnowledgeBaseStats,
  KnowledgeBasePermissions,
  KnowledgeDocument,
  DocumentMetadata,
  KnowledgeChunk,
  KnowledgeQuery,
  VectorSearchParams,
  KnowledgeSearchResult,
  KnowledgeStats,
  KnowledgeCategory,
  KnowledgeTag,
  KnowledgeImport,
  KnowledgeExport,
};
